package com.hancher.gamelife2.login;

import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.LinearLayout;

import androidx.navigation.Navigation;

import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.base.BaseMvpFragment;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.gamelife2.databinding.FragmentBaiduLoginBinding;
import com.hancher.gamelife2.home.HomePresenter;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebViewClient;

import java.math.BigDecimal;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class BaiduLoginFragment extends BaseMvpFragment<FragmentBaiduLoginBinding, HomePresenter> {

    public static final String URL = "URL";
    public static final String TITLE = "TITLE";
    /**
     * 当前token
     */
    public static final String BAIDUNET_ACCESS_TOKEN = "BAIDUNET_ACCESS_TOKEN";
    /**
     * 过期时间段
     */
    public static final String BAIDUNET_EXPIRES_IN = "BAIDUNET_EXPIRES_IN";
    /**
     * 过期时间戳
     */
    public static final String BAIDUNET_EXPIRATION_TIME = "BAIDUNET_EXPIRATION_TIME";
    private AgentWeb mAgentWeb;

    @Override
    protected void initView(Bundle savedInstanceState) {

        // 简化模式授权 https://pan.baidu.com/union/doc/6l0ryrjzv
        String url = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=token&client_id=" +
                "GZbtEzTVGcVfPMR80oxrFamY9zCPg2FX&scope=basic,netdisk&redirect_uri=oob&display=mobile";

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) binding.container, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                        // https://www.jianshu.com/p/c17029b0b67f Android Url&Uri详细解析
                        LogUtil.d("当前地址：" + request.getUrl());
                        if (request.getUrl() != null) {
                            Uri mUri = Uri.parse(request.getUrl().toString().replaceAll("login_success#", "login_success?"));
                            LogUtil.d(String.format("当前地址拆分 scheme=%s, host=%s, fragment=%s, query=%s：",
                                    mUri.getScheme(), mUri.getHost(), mUri.getFragment(), mUri.getQuery()));
                            if (request.getUrl().toString().startsWith("https://openapi.baidu.com/oauth/2.0/login_success")) {
                                String accessToken = mUri.getQueryParameter("access_token");
                                String expiresIn = mUri.getQueryParameter("expires_in");
                                LogUtil.d("百度网盘登录成功 token=%s  expire=%s", accessToken, expiresIn);
                                MmkvUtil.put(BaiduLoginFragment.BAIDUNET_ACCESS_TOKEN, accessToken);
                                MmkvUtil.put(BaiduLoginFragment.BAIDUNET_EXPIRES_IN, expiresIn);
                                BigDecimal time = new BigDecimal(expiresIn).multiply(new BigDecimal(1000)).add(BigDecimal.valueOf(System.currentTimeMillis()));
                                MmkvUtil.put(BaiduLoginFragment.BAIDUNET_EXPIRATION_TIME, time.longValue());
                                if (EmptyUtil.isNotEmpty(accessToken)) {
//                                    Intent data = new Intent();
//                                    data.putExtra(BaiduLoginFragment.BAIDUNET_ACCESS_TOKEN, accessToken);
//                                    data.putExtra(BaiduLoginFragment.BAIDUNET_EXPIRES_IN, expiresIn);
//                                    data.putExtra(BaiduLoginFragment.BAIDUNET_EXPIRATION_TIME, time.longValue());
                                    Navigation.findNavController(binding.container).popBackStack();
                                }
                            }
                        }
                        return super.shouldOverrideUrlLoading(view, request);
                    }

                })
                .createAgentWeb()
                .ready()
                .go(url);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }
}